package dao;

import anno.Autowired;
import anno.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import pojo.ExamPaper;
import pojo.Question;
import utils.JDBCUtils;
import utils.JsonUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 试卷DAO实现类
 */
@Component
public class ExamPaperDao extends AbstractBaseDao<ExamPaper> {

    @Autowired
    private QuestionDao questionDao;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 分页查询试卷列表
     */
    public List<ExamPaper> findPage(int pageNum, int pageSize, String keyword) throws SQLException {
        return executeWithConnection(() -> {
            // 1. 查询试卷列表
            StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName);
            List<Object> params = new ArrayList<>();

            if (keyword != null && !keyword.trim().isEmpty()) {
                sql.append(" WHERE paper_name LIKE ? OR description LIKE ?");
                params.add("%" + keyword.trim() + "%");
                params.add("%" + keyword.trim() + "%");
            }

            sql.append(" ORDER BY create_time DESC LIMIT ?, ?");
            params.add((pageNum - 1) * pageSize);
            params.add(pageSize);

            ResultSet rs = (ResultSet) JDBCUtils.execute(sql.toString(), params.toArray());
            List<ExamPaper> papers = new ArrayList<>();
            Set<Integer> allQuestionIds = new HashSet<>();

            // 收集试卷和题目ID
            while (rs.next()) {
                ExamPaper paper = mapResultSetToEntity(rs);
                try {
                    // 解析题目ID
                    String questionsJson = paper.getQuestions();
                    List<String> questionIdStrings = objectMapper.readValue(questionsJson,
                            objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));

                    // 收集所有题目ID
                    questionIdStrings.stream()
                            .map(Integer::parseInt)
                            .forEach(allQuestionIds::add);

                    paper.setQuestionList(new ArrayList<>());
                    papers.add(paper);
                } catch (JsonProcessingException | NumberFormatException e) {
                    throw new SQLException("Error processing question IDs", e);
                }
            }

            // 2. 如果有题目ID，查询题目信息
            if (!allQuestionIds.isEmpty()) {
                String questionSql = "SELECT * FROM tb_question WHERE question_id IN (" +
                        allQuestionIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";

                List<Object> questionParams = new ArrayList<>(allQuestionIds);
                ResultSet questionRs = (ResultSet) JDBCUtils.execute(questionSql, questionParams.toArray());

                // 将题目按ID映射
                Map<Integer, Question> questionMap = new HashMap<>();
                while (questionRs.next()) {
                    Question question = questionDao.mapResultSetToEntity(questionRs);
                    questionMap.put(question.getQuestionId(), question);
                }

                // 3. 为每个试卷组装题目列表
                for (ExamPaper paper : papers) {
                    try {
                        List<String> questionIdStrings = objectMapper.readValue(paper.getQuestions(),
                                objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));

                        List<Question> orderedQuestions = questionIdStrings.stream()
                                .map(idStr -> {
                                    Integer id = Integer.parseInt(idStr.trim());
                                    return questionMap.get(id);
                                })
                                .filter(Objects::nonNull)
                                .collect(Collectors.toList());

                        paper.setQuestionList(orderedQuestions);
                    } catch (JsonProcessingException e) {
                        throw new SQLException("Error processing question IDs", e);
                    }
                }
            }

            return papers;
        });
    }

    /**
     * 查询可用的试卷列表
     */
    public List<ExamPaper> findActivePapers() throws SQLException {
        return executeWithConnection(() -> {
            String sql = "SELECT * FROM " + tableName + " WHERE status = 1 ORDER BY create_time DESC";
            ResultSet rs = (ResultSet) JDBCUtils.execute(sql);
            List<ExamPaper> results = new ArrayList<>();
            while (rs.next()) {
                ExamPaper paper = mapResultSetToEntity(rs);

                // 获取题目列表
                try {
                    List<String> questionIdStrings = objectMapper.readValue(paper.getQuestions(),
                            objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
                    List<Integer> questionIds = questionIdStrings.stream()
                            .map(Integer::parseInt)
                            .collect(Collectors.toList());
                    List<Question> questions = questionDao.findByIds(questionIds);
                    paper.setQuestionList(questions);
                } catch (JsonProcessingException e) {
                    throw new SQLException("Error processing question IDs", e);
                }

                results.add(paper);
            }
            return results;
        });
    }

    /**
     * 统计符合条件的试卷总数
     */
    public long countByKeyword(String keyword) throws SQLException {
        return executeWithConnection(() -> {
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM " + tableName);
            List<Object> params = new ArrayList<>();

            if (keyword != null && !keyword.trim().isEmpty()) {
                sql.append(" WHERE paper_name LIKE ? OR description LIKE ?");
                params.add("%" + keyword.trim() + "%");
                params.add("%" + keyword.trim() + "%");
            }

            ResultSet rs = (ResultSet) JDBCUtils.execute(sql.toString(), params.toArray());
            return rs.next() ? rs.getLong(1) : 0;
        });
    }

    /**
     * 根据题目ID获取题目的分值
     */
    public int getQuestionScoreById(Integer questionId) throws SQLException {
        Question question = questionDao.findById(questionId);
        if (question != null && question.getScore() != null) {
            return question.getScore();
        } else {
            return 0;
        }
    }
    public ExamPaper findById(Integer paperId) throws SQLException {
        return executeWithConnection(() -> {
            String sql = String.format("SELECT * FROM %s WHERE paper_id = ?", tableName);
            ResultSet rs = (ResultSet) JDBCUtils.execute(sql, paperId);
            if (rs.next()) {
                ExamPaper paper = mapResultSetToEntity(rs);
                // 获取题目列表
                List<String> questionIdStrings = JsonUtils.parseJsonToList(paper.getQuestions());
                if (questionIdStrings != null && !questionIdStrings.isEmpty()) {
                    List<Integer> questionIds = questionIdStrings.stream()
                            .map(Integer::parseInt)
                            .collect(Collectors.toList());
                    List<Question> questions = questionDao.findByIds(questionIds);
                    paper.setQuestionList(questions);
                } else {
                    paper.setQuestionList(new ArrayList<>());
                }
                return paper;
            } else {
                return null;
            }
        });
    }

    /**
     * 根据题目ID列表获取题目的正确答案
     */
    public Map<Integer, String> getCorrectAnswersByQuestionIds(List<String> questionIds) throws SQLException {
        Map<Integer, String> correctAnswers = new HashMap<>();
        if (questionIds == null || questionIds.isEmpty()) {
            return correctAnswers;
        }

        String placeholders = questionIds.stream().map(id -> "?").collect(Collectors.joining(","));
        String sql = "SELECT question_id, correct_answer FROM tb_question WHERE question_id IN (" + placeholders + ")";

        List<Object> params = questionIds.stream().map(Integer::valueOf).collect(Collectors.toList());
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, params.toArray());

        while (rs.next()) {
            Integer questionId = rs.getInt("question_id");
            String correctAnswer = rs.getString("correct_answer");
            correctAnswers.put(questionId, correctAnswer);
        }

        return correctAnswers;
    }

    /**
     * 保存试卷
     */
    @Override
    public Integer insert(ExamPaper paper) throws SQLException, JsonProcessingException {
        // 在插入之前，计算总分
        List<String> questionIds = objectMapper.readValue(paper.getQuestions(),
                objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
        int totalScore = 0;
        for (String qIdStr : questionIds) {
            Integer qId = Integer.parseInt(qIdStr.trim());
            totalScore += getQuestionScoreById(qId);
        }
        paper.setTotalScore(totalScore);

        return super.insert(paper);
    }

    /**
     * 更新试卷
     */
    @Override
    public boolean update(ExamPaper paper) throws SQLException, JsonProcessingException {
        // 在更新之前，计算总分
        List<String> questionIds = objectMapper.readValue(paper.getQuestions(),
                objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
        int totalScore = 0;
        for (String qIdStr : questionIds) {
            Integer qId = Integer.parseInt(qIdStr.trim());
            totalScore += getQuestionScoreById(qId);
        }
        paper.setTotalScore(totalScore);

        return super.update(paper);
    }
}
